package org.ainlolcat.ainscience.transformer;

import org.ainlolcat.ainscience.column.Column;
import org.ainlolcat.ainscience.entity.Entity;
import org.ainlolcat.ainscience.matrix.MatrixFileParser;
import org.jdom.Element;

/**
 * Created by IntelliJ IDEA.
 * User: ain
 * Date: 11/5/11
 * Time: 9:54 PM
 * subtract from data set line which plotted by end and start of data set
 */
public class BaseLineTransformer implements Transformer {

    //count of dot which will be getData for performing calculation of baseline
    private int dotCount = 70;

    public void handle(Entity entity, Integer columnID) {
        Column cy = entity.getColumnByOrder(columnID);
        Column cx = entity.getXColumn(cy.getAxis());
        if (cx.isNumeric()&&cy.isNumeric()){
            if (cx.size()>dotCount*2&&cx.size() == cy.size()){
                double startX = 0;
                double startY = 0;
                double endX = 0;
                double endY = 0;
                double[] x = cx.getDoubleRepresentation();
                double[] y = cy.getDoubleRepresentation();
                for (int i=0;i<dotCount;i++){
                    startX += x[i];
                    startY += y[i];
                    endX +=x[x.length-i-1];
                    endY +=y[y.length-i-1];
                }
                startX = startX / dotCount;
                startY = startY / dotCount;
                endX = endX / dotCount;
                endY = endY / dotCount;
                double k = (endY - startY)/(endX-startX);
                //y=startY + k * x ;
                if (cy.getType().equals(MatrixFileParser.MATRIX_DELIMETER_TYPE_DOUBLE)){
                    for (int i=0;i<cy.size();i++){
                        double newval = y[i] - ( startY + k*(x[i]-startX) );
                        cy.setValueAt(i, new Double( newval));
                    }
                }
                if (cy.getType().equals(MatrixFileParser.MATRIX_DELIMETER_TYPE_INTEGER)){
                    for (int i=0;i<cy.size();i++){
                        int newval = (int)Math.round(y[i] - ( startY + k*(x[i]-startX) ));
                        cy.setValueAt(i, new Integer( newval));
                    }
                }
            }
        }
    }

    public void handle(Entity entity, Integer columnID, Element params) {
        handle(entity, columnID);
    }
}
